#include "cgzCLua.h"
#include "cgzCTimer.h"
#include "cgzCThreadPool.h"

static int timeout(lua_State *L)
{
    // 将其转换为 cgzCLua 指针
    cgzCLua *that = cgzCLua::getThat(L);
    int id = lua_tointeger(L, 1);
    int ms = lua_tointeger(L, 2);
    void *node = malloc(sizeof(tagTimer));
    auto pTimer = new (node) tagTimer(id, ms);
    that->regTask("cgzCTimer", pTimer);
    return 0;
}

/// @brief 创建一个预分配好的lua表
/// @param L
/// @return
static int tcreate(lua_State *L)
{
    int narr = lua_tointeger(L, 1);
    int nrec = lua_tointeger(L, 2);
    lua_createtable(L, narr, nrec); // 创建一个空表
    return 1;
}

static int tabdate(lua_State *L)
{
    time_t t = luaL_checkinteger(L, 1);
    auto *stm = localtime(&t);
    lua_cgz_newh(L, 9);
    lua_pushinteger(L, stm->tm_year + 1900);
    lua_setfield(L, -2, "year");
    lua_pushinteger(L, stm->tm_mon + 1);
    lua_setfield(L, -2, "month");
    lua_pushinteger(L, stm->tm_mday);
    lua_setfield(L, -2, "day");
    lua_pushinteger(L, stm->tm_hour);
    lua_setfield(L, -2, "hour");
    lua_pushinteger(L, stm->tm_min);
    lua_setfield(L, -2, "min");
    lua_pushinteger(L, stm->tm_sec);
    lua_setfield(L, -2, "sec");
    lua_pushinteger(L, stm->tm_yday + 1);
    lua_setfield(L, -2, "yday");
    lua_pushinteger(L, stm->tm_wday + 1);
    lua_setfield(L, -2, "wday");
    lua_pushboolean(L, stm->tm_isdst);
    lua_setfield(L, -2, "isdst");
    return 1;
}

static int lreload(lua_State *L)
{
    cgzCLua *that = cgzCLua::getThat(L);
    that->reload();
    return 0;
}

static int nowsec(lua_State *L)
{
    lua_pushinteger(L, fnowsec());
    return 1;
}

static int nowmls(lua_State *L)
{
    lua_pushinteger(L, fnowmls());
    return 1;
}

static int nowmcs(lua_State *L)
{
    lua_pushinteger(L, fnowmcs());
    return 1;
}

static int difsec(lua_State *L)
{
    long sec = lua_tointeger(L, 1);
    lua_pushinteger(L, fdifsec(sec));
    return 1;
}

int cgzCLua::luaopen_other(lua_State *L)
{
    static const luaL_Reg otherlib[] = {
        {"timeout", timeout},
        {"tcreate", tcreate},
        {"tabdate", tabdate},
        {"lreload", lreload},
        {"nowsec", nowsec},
        {"nowmls", nowmls},
        {"nowmcs", nowmcs},
        {"difsec", difsec},
        {NULL, NULL}};

    luaL_newlib(L, otherlib);
    return 1;
}
